package com.roubsite.admin.dao.rsRoleMenu;

import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.roubsite.admin.bean.RsRoleMenu;
import com.roubsite.admin.bean.ZTree;
import com.roubsite.database.bean.Record;
import com.roubsite.database.dao.DataSet;
import com.roubsite.database.dao.EntityDao;
import com.roubsite.utils.UuidUtils;

public class RsRoleMenuDao extends EntityDao implements IRsRoleMenuDao {

	@Override
	public DataSet getInfoById(String id) {
		DataSet ds = this.queryBean("SELECT * FROM RS_ROLE_MENU WHERE ID =?", new String[] { id },
				new int[] { Types.VARCHAR }, false, 0, 0, RsRoleMenu.class);
		return ds;
	}

	@Override
	public DataSet queryd(Record record, int start, int rows) {
		return this.queryBean(record.toBean(RsRoleMenu.class), null, true, start, rows);
	}

	@Override
	public int saveData(Record record, Class<?> bean) {
		return this.save(record, bean);
	}

	@Override
	public int del(List ids) throws Exception {
		String tableName = "RS_ROLE_MENU";
		String keyField = "ID";
		StringBuffer delSql = new StringBuffer("DELETE FROM " + tableName + " WHERE " + keyField + " IN (");
		for (int i = 0; i < ids.size(); i++) {
			delSql.append("'");
			delSql.append(ids.get(i));
			delSql.append("',");
		}
		String sql = delSql.substring(0, delSql.length() - 1);
		sql = sql + ")";

		return this.excute(sql, new Object[] {}, new int[] {});
	}

	@Override
	public List<ZTree> getRoleMenuTree(String roleId) {
		List<Map<String, Object>> menuList = this.query("SELECT MENU_ID,PARENT_ID,MENU_NAME FROM RS_MENU ORDER BY ORDER_ID ASC", null,
				null);
		List<Map<String, Object>> roleMenuList = this.query("SELECT MENU_ID FROM RS_ROLE_MENU WHERE ROLE_ID = ?",
				new String[] { roleId }, new int[] { Types.VARCHAR });
		List<ZTree> tree = new ArrayList<>();
		for (Map<String,Object> menu : menuList) {
			ZTree t = new ZTree();
			String menuId = (String) menu.get("MENU_ID");
			t.setId(menuId);
			t.setName((String) menu.get("MENU_NAME"));
			t.setpId((String) menu.get("PARENT_ID"));

			Map<String,Object> tmpMenu = new HashMap<>();
			tmpMenu.put("MENU_ID", menuId);
			if (roleMenuList.contains(tmpMenu)) {
				t.setChecked(true);
				t.setOpen(true);
			} else {
				t.setChecked(false);
			}
			tree.add(t);
		}

		return tree;
	}

	@Override
	public int delByRoleId(String roleId) {
		return this.excute("DELETE FROM RS_ROLE_MENU WHERE ROLE_ID = ?", new String[] { roleId },
				new int[] { Types.VARCHAR });
	}

	@Override
	public int insertRoleMenu(String roleId, List<String> menuIds) {

		for (String menuId : menuIds) {
			String sql = "INSERT INTO RS_ROLE_MENU (ID,ROLE_ID,MENU_ID) VALUES (?,?,?)";
			super.excute(sql, new String[] { UuidUtils.getUuid(), roleId, menuId },
					new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
		}
		return 1;
	}

}
